package me.youline.dataServer.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.youline.dataServer.service.authentication.UserAuthenticationToken;
import me.youline.dataServer.service.support.MsgBuilder;
import me.youline.dataServer.utils.ResponseTypeOutputUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpHeaders;

public class UserTokenAuthcFilter extends AccessControlFilter {

	private static final String TOKEN_NAME = "token";

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		((HttpServletRequest) request).getRequestURI();
		UserAuthenticationToken token = new UserAuthenticationToken(
				getToken(request));
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			return false;
		}
		return subject.isAuthenticated();
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletResponse res = (HttpServletResponse) response;
		res.setStatus(HttpServletResponse.SC_FORBIDDEN);
		res.addHeader(HttpHeaders.WWW_AUTHENTICATE, "/login");
		String errorMsg = MsgBuilder.error().errorCode("200101")
				.errorMsg("用户账户未经验证，服务器拒绝访问")
				.reqUrl(((HttpServletRequest) request).getRequestURI())
				.toJSONString();
		ResponseTypeOutputUtils.renderJson(res, errorMsg);
		return false;
	}

	/**
	 * 从http请求中获取token字符串
	 * @param request
	 * @return
	 */
	private String getToken(ServletRequest request) {
		return request.getParameter(TOKEN_NAME);
	}

}
